--
-- Author: yawei.zhu
-- Date: 2018-05-08 11:06:41
--
-- DailyTaskPanel
--

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local DailyTaskRender = import(".renders.DailyTaskRender")

local ClassRef = app.mvc.createPanelClass(...)

local percent_1_start = 39
local percent_1_end = 50
local percent_2_start = 69
local percent_2_end = 80
local percent_3 = 100

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.TaskDailyNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._dailyListView = self._ui["Panel/ListView"]
    self._dailyListView:removeAllItems()

    self._hideEntry = UD.setting:getIsHideDailyTaskEntry()
    local btn = self._ui["Panel/Panel_top/selected_btn"]
    btn:setBright(self._hideEntry)
    btn:addClickEventListener(function()
        self._hideEntry = not self._hideEntry
        print(self._hideEntry)
        btn:setBright(self._hideEntry)
        UD.setting:setHideDailyTaskEntry(self._hideEntry)

        if self._hideEntry then
            UIHandler:removeOpenFunctionId(Constant.FUNC_TYPE_TASK_DAILY)
        else
            UIHandler:addOpenFunctionId(Constant.FUNC_TYPE_TASK_DAILY, nil, true)
        end
    end)

    self._giftPanel1 = self._ui["Panel/Panel_top/gift_1/Panel"]  -- 引导的时候会把该node移除掉，所以这里先暂存
end

function ClassRef:refresh()
    local dailyTasks = executeFunc(self._onOperate, "getDailyTasks")
    -- print("111111")
    --print(#dailyTasks)
    for i = 1, #dailyTasks do
        local render = DailyTaskRender.create()
        render:onBtnClick(self._onOperate)
        render:setTaskType("daily")
        render:setData(dailyTasks[i])
        self._dailyListView:pushBackCustomItem(render)
    end
    self._dailyListView:refreshView()

    -- 设置LoadingBar初始进度为0
    local loadingBar = self._ui["Panel/Panel_top/bar/LoadingBar"]
    loadingBar:setPercent(0)
end

function ClassRef:updateDailyTasksShow(taskId)
    if not taskId then return end

    local taskInfo = UD:getTaskById(taskId)
    if not taskInfo then return end

    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        if item:getData():getId() == taskId then
            item:setData(taskInfo)
            break
        end
    end
end

function ClassRef:updateDailyTaskProgress()
    -- print("updateDailyTaskProgress")
    
    local dailyTasks = executeFunc(self._onOperate, "getDailyTasks")
    self:updateNewTasks(dailyTasks, true)


    local Panel_top = self._ui["Panel/Panel_top"]
    local progressBar = self._ui["Panel/Panel_top/bar/LoadingBar"]
    local finishedNumText = Panel_top:getChildByName("num")

       
    local totalNumber = executeFunc(self._onOperate, "getTotalDailyTaskNumber")
    local finishedNumber = executeFunc(self._onOperate, "getFinishedDailyTaskNumber")

    local dailyTaskInfo = TaskManager:getDailyTaskInfo()
    local progress = dailyTaskInfo:getDailyTaskProgress()
    local arrStr = {progress[1].NeedProgress, progress[2].NeedProgress, progress[3].NeedProgress}
    local value1, value2, value3 = tonumber(arrStr[1]), tonumber(arrStr[2]), tonumber(arrStr[3])

    -- print(value1 .. value2 .. value3)

    local percent = finishedNumber / totalNumber * 100
    if finishedNumber <= value1 then
        percent = percent_1_start * (finishedNumber / value1)
    elseif finishedNumber <= value2 then
        percent = percent_1_end + ( percent_2_start - percent_1_end ) * ((finishedNumber - value1) / (value2 - value1))
    else
        percent = percent_2_end + ( percent_3 - percent_2_end ) * ((finishedNumber - value2) / (value3 - value2))
    end

    progressBar:setPercent(percent)
    finishedNumText:setString(finishedNumber)

    for i = 1, 3 do
        local name = "gift_" .. i
        local giftPanel

        if i == 1 then 
            giftPanel = self._giftPanel1
        else
            local giftNode = Panel_top:getChildByName(name)
            giftPanel = giftNode:getChildByName("Panel")
        end

        local maskLock = giftPanel:getChildByName("mask_lock")
        maskLock:setVisible(false)
        maskLock:setTouchEnabled(false)

        for j = 1, 3 do
            local boxName = "icon_" .. j
            local boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)

            boxName = "icon_".. j .. "_o"
            boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)
        end

        local bottomNumText = giftPanel:getChildByName("num_1")
        local getNumText = giftPanel:getChildByName("num_2")
        local blackBg = giftPanel:getChildByName("bg_num2")
        local redBg = giftPanel:getChildByName("bg_num3")
        getNumText:setVisible( false )
        blackBg:setVisible(false)
        redBg:setVisible(false)

        local rewardProgress = self._onOperate("getDailyTaskRewardProgress", tonumber(arrStr[i]))
        if rewardProgress then
            bottomNumText:setString( rewardProgress.NeedProgress )
            getNumText:setString( rewardProgress.NowProgress )

            if rewardProgress.NowProgress > 0 then -- 奖励累积次数 > 0？
                getNumText:setVisible(true)
                giftPanel:getChildByName("icon_" .. i):setVisible(true)

                local isLock = false
                if finishedNumber < tonumber(rewardProgress.NeedProgress) then -- 未解锁
                    isLock = true
                    blackBg:setVisible(true)
                    maskLock:setVisible(true)
                else
                    redBg:setVisible(true)
                end

                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)
                    local params = {}
                    params.lock = isLock
                    params.nowProgress = rewardProgress.NowProgress
                    params.needProgress = rewardProgress.NeedProgress
                    params.boxIndex = rewardProgress.boxIndex
                    params.questType = 5
                    executeFunc(self._onOperate, "OPEN_REWARD", params)
                end)
            else
                giftPanel:getChildByName("icon_"..i.."_o"):setVisible(true)
                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)end)
                giftPanel:addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.began then
                        local dataInfoTemp = {
                            name = L("dailyTreasureName"),
                            string1 = string.format(L("dailyTreasureDes"),S("daystartsat")),
                            string4 = L("dailyTreasureWarning"),
                        }
                        if self._rareInfoPanel then
                            self._rareInfoPanel:setData( dataInfoTemp )
                        else
                            self._rareInfoPanel = NewRareInfoView.create()
                            self._rareInfoPanel:setData( dataInfoTemp )
                            UIHandler:addPopupUi(self._rareInfoPanel)
                        end
                        local triggerNodeBoundingBox = giftPanel:getBoundingBox()
                        local worldPosTemp = giftPanel:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
                        triggerNodeBoundingBox.x = worldPosTemp.x
                        triggerNodeBoundingBox.y = worldPosTemp.y
                        display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
                    elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
                        if self._rareInfoPanel then
                            self._rareInfoPanel:removeFromParent()
                            self._rareInfoPanel = nil
                        end
                    end
                end)
            end
        end
    end
end

function ClassRef:updateNewTasks(tasks, notSend)
    local hasFinish = false
    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local taskId = item:getData():getId()
        for __, task in pairs(tasks) do
            if task:getId() == taskId then
                item:setData(task)

                if task:isFinished() then
                    hasFinish = true
                end
                break
            end
        end
    end

    -- 如果有日常任务完成，需要重新拉取完成进度
    if hasFinish and not notSend then
        executeFunc(self._onOperate, "GET_DAILY_INFO")
    end
end

function ClassRef:refreshDailyTask(pos)
    local task = UD:getDailytTaskByPos(pos)
    if not task then return end

    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local oldPos = item:getData():getPos()
        if oldPos == pos then
            --dump(oldPos)
            item:setData(task)
        end
    end
end

function ClassRef:playDailyRefreshAni(pos)
    local render
    local items = self._dailyListView:getItems()
    for _, item in ipairs(items) do
        local oldPos = item:getData():getPos()
        if oldPos == pos then
            render = item 
            break
        end
    end
    if not render then return end

    local panel = render:getChildByName("Panel")
    panel:removeChildByName( "_refreshAnimationTemp" )
    local amiNodeTemp = cc.CSLoader:createNode( Res.DailyTaskRefreshAmi )
    amiNodeTemp:setName( "_refreshAnimationTemp" )
    amiNodeTemp:setPosition( panel:getChildByName("ani_refresh"):getPosition() )
    panel:addChild( amiNodeTemp )
    amiNodeTemp:getTimeline():gotoFrameAndPlay( 0, false )

    local actions = {}
    table.insert( actions, cc.DelayTime:create( amiNodeTemp:getTimeline():getDuration()/60 * 0.5) )
    table.insert( actions, cc.CallFunc:create( function() self:refreshDailyTask(pos) end ) )
    table.insert( actions, cc.DelayTime:create( amiNodeTemp:getTimeline():getDuration()/60 * 0.5) )
    table.insert( actions, cc.CallFunc:create( function() amiNodeTemp:removeFromParent() end ) )
    table.insert( actions, cc.RemoveSelf:create() )
    amiNodeTemp:runAction( cc.Sequence:create( actions ) )
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
